import random
import time
import paho.mqtt.client as mqtt


class MQTTClient:
    def __init__(self, broker, port,client_id, topic, username=None, password=None):
        self.broker = broker
        self.port = port
        self.topic = topic
        self.username = username
        self.password = password
        self.client_id = client_id
        self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id)

        # 设置用户名和密码
        if self.username and self.password:
            self.client.username_pw_set(self.username, self.password)

        self.client.on_connect = self.on_connect
        self.client.on_msg = self.on_msg
        self.client.on_disconnect = self.on_disconnect

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
            self.client.subscribe(self.topic)
        else:
            print(f"Failed to connect, return code {rc}")

    def on_msg(self, client, userdata, msg):
        msg = msg.payload.decode()
        print(f"Received msg: {msg} from topic {msg.topic}")

    def on_disconnect(self, client, userdata, rc):
        print(f"Disconnected from MQTT Broker with code {rc}")

    def connect(self):
        self.client.connect(self.broker, self.port)
        self.client.loop_start()


    def publish(self, topic, msg):
        self.client.publish(topic, msg)
        print(f"Published msg: {msg} to topic {topic}")

    def subscribe(self, topic):
        self.client.subscribe(topic)
        print(f"Subscribed to topic: {topic}")

    def start_loop(self):
        print("Starting MQTT loop...")
        self.client.loop_start()

    def stop_loop(self):
        self.client.loop_stop()
        self.client.disconnect()

    def set_callback(self, callback):
        self.client.on_msg = callback
# 示例使用
if __name__ == "__main__":
    broker = '192.168.0.13'
    port = 1883
    topic = "topic"
    username = None
    password = None
    client_id= "test_client"
    # 创建 MQTT 客户端实例
    mqtt_client = MQTTClient(broker, port,client_id, topic, username, password)

    # 连接到 MQTT 代理
    mqtt_client.connect()

    # 发送消息
    mqtt_client.publish(topic, "Hello, 加菲猫将军!")
    mqtt_client.set_callback

    # 保持连接
    try:
        mqtt_client.start_loop()
    except KeyboardInterrupt:
        mqtt_client.set_callback()
